import { useState, useCallback, useRef } from "react";

// 样式常量
const DRAGGABLE_STYLES = {
  base: "absolute cursor-move shadow-lg flex items-center justify-center",
  size: "w-8 h-8 md:w-12 md:h-12",
  stickSize: "w-20 h-20 md:w-24 md:h-24",
  shape: "rounded-full",
  color: "bg-transparent",
};

const Draggable = ({
  center = false,
  position,
  onDrag,
  onPointer,
  onDelete,
  onSettings,
  children,
  hasSetting = false,
}) => {
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const [pos, setPos] = useState({ x: position.x, y: position.y });
  const [isDragging, setIsDragging] = useState(false);
  const draggableRef = useRef(null);

  // 获取事件位置（兼容鼠标和触摸事件）
  const getEventPosition = (e) => {
    return e.type.includes("touch") ? e.touches[0] : e;
  };

  // 开始拖动
  const handleStart = useCallback(
    (e) => {
      const event = getEventPosition(e);
      setIsDragging(true);

      const rect = e.currentTarget.getBoundingClientRect();
      setOffset({
        x: center ? event.clientX - pos.x : event.clientX - rect.left,
        y: center ? event.clientY - pos.y : event.clientY - rect.top,
      });

      onPointer?.();
    },
    [onPointer]
  );

  // 拖动中
  const handleMove = useCallback(
    (e) => {
      if (!isDragging) return;

      const event = getEventPosition(e);
      // const newPos = {
      //   x: event.clientX - offset.x,
      //   y: event.clientY - offset.y,
      // };
      let newX = event.clientX - offset.x;
      let newY = event.clientY - offset.y;
      const { width, height } =
        draggableRef.current.parentNode.getBoundingClientRect();
      // 应用边界检查
      if (width > 0 && height > 0) {
        newX = Math.max(0, Math.min(newX, width - 10));
        newY = Math.max(0, Math.min(newY, height - 10));
      }

      const newPos = { x: newX, y: newY };

      setPos(newPos);
      onDrag?.(e, newPos);
    },
    [isDragging, offset, onDrag]
  );

  // 结束拖动
  const handleEnd = useCallback(() => {
    setIsDragging(false);
  }, []);

  // 组合样式
  const combinedStyles = {
    left: `${pos.x}px`,
    top: `${pos.y}px`,
    ...(center && { transform: "translate(-50%, -50%)" }),
    touchAction: "none", // 防止移动端触摸滚动
  };

  // SVG图标定义
  const DELETE_ICON = (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <line x1="18" y1="6" x2="6" y2="18"></line>
      <line x1="6" y1="6" x2="18" y2="18"></line>
    </svg>
  );

  const SETTINGS_ICON = (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="12" cy="12" r="3"></circle>
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
    </svg>
  );

  return (
    <div
      ref={draggableRef}
      className={`${DRAGGABLE_STYLES.base} ${
        hasSetting ? DRAGGABLE_STYLES.stickSize : DRAGGABLE_STYLES.size
      } ${DRAGGABLE_STYLES.shape} ${DRAGGABLE_STYLES.color}`}
      style={combinedStyles}
      onMouseDown={handleStart}
      onTouchStart={handleStart}
      onMouseMove={handleMove}
      onTouchMove={handleMove}
      onMouseUp={handleEnd}
      onTouchEnd={handleEnd}
      onMouseLeave={handleEnd}
    >
      {/* 删除按钮 */}
      <button
        className="absolute -top-1 right-0 text-white bg-mask hover:bg-red-600 z-10"
        onClick={(e) => {
          e.stopPropagation();
          onDelete?.();
        }}
        aria-label="删除"
      >
        {DELETE_ICON}
      </button>

      {/* 设置按钮 */}
      {hasSetting && (
        <button
          className="absolute -top-1 left-0 text-white bg-mask hover:bg-gray-600  z-10"
          onClick={(e) => {
            e.stopPropagation();
            onSettings?.();
          }}
          aria-label="设置"
        >
          {SETTINGS_ICON}
        </button>
      )}

      {children}
    </div>
  );
};

export default Draggable;
